package com.cloud.admin.influxdb;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.influxdb.InfluxDB;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class MetricsRepository {
    private static final String MEASUREMENT_NAME = "sentinel_metric";

    @Autowired
    public InfluxDB influxDB;

    public synchronized void saveAll(List<MetricEntity> metrics) {
        if (CollectionUtils.isEmpty(metrics)) {
            return;
        }
        BatchPoints batchPoints = BatchPoints.builder().consistency(InfluxDB.ConsistencyLevel.ALL).build();
        metrics.forEach(metric -> batchPoints.point(createPoint(metric)));
        try {
            influxDB.write(batchPoints);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private Point createPoint(MetricEntity metric) {
        return Point.measurement(MEASUREMENT_NAME)
                .time(metric.getTimestamp(), TimeUnit.MILLISECONDS)
                .tag(MetricEntity.APP, metric.getApp())
                .tag(MetricEntity.INSTANCE, metric.getInstance())
                .tag(MetricEntity.RESOURCE, metric.getResource())
                .addField(MetricEntity.GMT_CREATE, metric.getGmtCreate())
                .addField(MetricEntity.GMT_MODIFIED, metric.getGmtModified())
                .addField(MetricEntity.TIMESTAMP, metric.getTimestamp())
                .addField(MetricEntity.PASS_QPS, metric.getPassQps())
                .addField(MetricEntity.SUCCESS_QPS, metric.getSuccessQps())
                .addField(MetricEntity.BLOCK_QPS, metric.getBlockQps())
                .addField(MetricEntity.EXCEPTION_QPS, metric.getExceptionQps())
                .addField(MetricEntity.RT, metric.getRt())
                .addField(MetricEntity.COUNT, metric.getCount())
                .addField(MetricEntity.RESOURCE_CODE, metric.getResourceCode())
                .build();
    }
}
